package com.google.monkeyjump.db;

import com.google.monkeyjump.ranking.Rank;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import util.Constants;

public class DataBaseHelper extends SQLiteOpenHelper{

	public DataBaseHelper(Context context) {
		super(context, Constants.DATABASE_NAME, null, Constants.SCHEMA_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase dataBase) {
		dataBase.execSQL("CREATE TABLE " + Constants.RANK_TABLE_NAME 
				+ " (" + Constants.RANK_ID_COLUMN_NAME +" INTEGER PRIMARY KEY AUTOINCREMENT, "
				+ Constants.RANK_USER_COLUMN_NAME + " TEXT NOT NULL, "
				+ Constants.RANK_POINTS_COLUMN_NAME + " integer NOT NULL);");
	}

	@Override
	public void onUpgrade(SQLiteDatabase dataBase, int oldVersion, int newVersion) {
		dataBase.execSQL("DROP TABLE if exists " + Constants.RANK_TABLE_NAME + ";");
	}
	
	public void insert(Rank rank) {
		insertRankInTable(rank);
		
		if ( hasDataBaseReachedLimits() ) {
			removeLastRank();
		}
		
	}

	private void insertRankInTable(Rank rank) {
		ContentValues contentValues = new ContentValues();
		
		contentValues.put(Constants.RANK_POINTS_COLUMN_NAME, 
				rank.getPoints());
		
		contentValues.put(Constants.RANK_USER_COLUMN_NAME, 
				rank.getUser());
		
		getWritableDatabase().
			insert(Constants.RANK_TABLE_NAME, null, contentValues);
	}
	
	private void removeLastRank() {
		long id = getIdOflastRank();
		getWritableDatabase().
				delete(Constants.RANK_TABLE_NAME, 
						Constants.RANK_ID_COLUMN_NAME + " = " + id, null);
	}
	
	private long getIdOflastRank() {
		Cursor ranksCursor = getReadableDatabase().
				query(Constants.RANK_TABLE_NAME, 
				new String[]{Constants.RANK_ID_COLUMN_NAME}, null, null, null, null, 
				Constants.RANK_POINTS_COLUMN_NAME, "1");
		
		ranksCursor.moveToFirst();
		long id = ranksCursor.getLong(0);
		
		ranksCursor.close();
		
		return id;
	}
	
	private boolean hasDataBaseReachedLimits() {
		return  countTableRows(Constants.RANK_TABLE_NAME) > Constants.RANK_SIZE_LIMIT;
	}
	
	private int countTableRows(String tableName){
		Cursor countRows = getReadableDatabase().
				rawQuery("SELECT count(*) FROM " + tableName, null);
		
		countRows.moveToFirst();
		int count = countRows.getInt(0);
		countRows.close();
		
		return count;
	}

}
